package com.maruping.disk.spring.security;

import com.maruping.disk.login.service.LoginService;
import com.maruping.disk.mybatis.entity.PtUserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@Service
public class GdmtUserDetailsService implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private LoginService loginService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取当前请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 检查错误次数，>=3时验证验证码
        Integer errorCount = (Integer) request.getSession().getAttribute("loginErrorCount");
        if (errorCount != null && errorCount >= 3) {
            String inputCaptcha = request.getParameter("captcha");
            String sessionCaptcha = (String) request.getSession().getAttribute("sessionCaptcha");

            if (inputCaptcha == null || !inputCaptcha.equalsIgnoreCase(sessionCaptcha)) {
                throw new UsernameNotFoundException("验证码错误");
            }
        }

        // 原有用户验证逻辑
        PtUserEntity ptUserEntity = loginService.queryUserInfoByName(username);
        if (ptUserEntity == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<String> permissionList = loginService.queryPermissionList(ptUserEntity.getUserUuid());
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissionList) {
            authorities
                    .add(new SimpleGrantedAuthority("ROLE_" + permission));
        }

        return new UserDiskEntity(ptUserEntity, authorities);

    }
}